/*
 * @Author: 卢景滔
 * @Date: 2021-12-21 10:11:50
 * @LastEditTime: 2021-12-21 14:47:05
 * @LastEditors: 卢景滔
 * @Description: 子线程
 */

// 接收主线程信息
self.addEventListener('message', (e) => {
  const res = e.data
  switch (res.cmd) {
    case 'to child':
      console.log('子线程收到主线程信息：', res.data)
      postMessage({ cmd: 'to father', data: 'I am fine, father.' })
      break

    case `to child's child`:
      console.log('子线程收到主线程信息：', res.data)
      createChildThread()
      break

    case `test error`:
      console.log('子线程收到主线程信息：', res.data)
      throw new Error('child error')
      break
  }
})

function createChildThread() {
  const childThread = new Worker('child/ChildThread.js')
  childThread.postMessage({ cmd: 'to child', data: 'How are you, child?' })

  // 监听子线程信息
  childThread.addEventListener('message', (e) => {
    const res = e.data
    switch (res.cmd) {
      case 'to father':
        console.log('子线程收到子线程信息: ', res.data)
        postMessage({ cmd: `to father's father`, data: `I am fine, father's father.` })
        break
    }
  })
}
